<template>
  <div class="main-container">
    <fm-nav-bar
      title="普通主子表"
      left-text=""
      right-text=""
      left-arrow
      @click-left="$router.go(-1)"
    />
    <div
      :class="['main', type != 'view' ? 'with-button' : 'without-button']"
      v-if="loading"
    >
      <fm-form :readonly="isDisabled" class="cus-form">
        <fm-field
          input-align="right"
          v-model="formData.name"
          name="采购计划名称"
          label="采购计划名称"
          :maxlength="50"
          :placeholder="isDisabled ? '' : '请输入内容'"
        />
        <div>
          <fm-field
            :is-link="!isDisabled"
            input-align="right"
            clickable
            name="calendar"
            :value="formData.createDate"
            label="采购计划日期"
            :placeholder="isDisabled ? '' : '请选择'"
            readonly
            @click.stop.native="isDisabled ? '' : (showCalendar = true)"
          />
          <fm-calendar
            :disabled="isDisabled"
            v-model="showCalendar"
            @confirm="onCalendarConfirm"
            :confirm-button-style="{ height: '44p;', marginBottom: '10px' }"
          />
        </div>
        <div>
          <fm-field name="stepper" label="采购预算" input-align="right">
            <template #input>
              <fm-stepper
                @change="stepperChange"
                input-width="50"
                :disabled="isDisabled"
                min="0"
                v-model="formData.expense"
              />
            </template>
          </fm-field>
        </div>
        <div>
          <fm-field
            :is-link="!isDisabled"
            readonly
            clickable
            input-align="right"
            name="picker"
            :value="formData.reimburseType | transferEnum('reimburse_type')"
            label="采购类型"
            :placeholder="isDisabled ? '' : '请选择'"
            @click.stop.native="isDisabled ? '' : (showPicker = true)"
          />
          <fm-popup :visible.sync="showPicker" position="bottom">
            <fm-picker
              title="采购类型"
              confirm-button-text="完成"
              show-toolbar
              :columns="reimburseType"
              :value-key="lang"
              @confirm="onReimburseTypeConfirm"
              @cancel="showPicker = false"
            />
          </fm-popup>
        </div>
        <div class="textarea-type">
          <fm-cell-group title="采购说明">
            <fm-field
              v-model="formData.description"
              type="textarea"
              maxlength="50"
              :readonly="isDisabled"
              :placeholder="isDisabled ? '' : '请输入内容'"
              show-word-limit
            />
          </fm-cell-group>
        </div>
        <fm-field name="checkboxGroup" label="通知方式" input-align="right">
          <template #input>
            <fm-checkbox-group
              v-model="checkboxGroup"
              direction="horizontal"
              @change="checkbox"
            >
              <fm-checkbox :disabled="true" name="短信" shape="square"
                >短信</fm-checkbox
              >
              <fm-checkbox :disabled="isDisabled" name="邮箱" shape="square"
                >邮箱</fm-checkbox
              >
            </fm-checkbox-group>
          </template>
        </fm-field>
        <!-- <uploader
          v-model="formData.attachment"
          :deletable="!isDisabled"
          :disabled="isDisabled"
          @fileChange="fileChange"
          :showUpload="!isDisabled"
          ref="attachment"
          type="image"
          class="uploder-attachment"
        /> -->
        <select-user
          title="采购负责人"
          :userFullname.sync="formData.managerFullname"
          :userName.sync="formData.manager"
          :disabled="isDisabled"
          :multiple="false"
          :required="true"
        >
        </select-user>
        <!-- <select-personnel
          title="selectPersonnel-单选"
          :userName.sync="name1"
          :userFullname.sync="fullname1"
          :disabled="isDisabled"
          :required="true"
        >
        </select-personnel>
        <select-personnel
          title="selectPersonnel-多选"
          :userName.sync="name2"
          :userFullname.sync="fullname2"
          :disabled="isDisabled"
          :multiple="true"
          :required="true"
        >
        </select-personnel> -->
        <select-user
          title="财务审批人"
          :userFullname.sync="formData.financeAssigneeFullname"
          :userName.sync="formData.financeAssignee"
          :disabled="isDisabled"
          :multiple="false"
          :required="true"
        ></select-user>
        <select-user
          title="经理审批人"
          :userFullname.sync="formData.manageAssigneeFullname"
          :userName.sync="formData.manageAssignee"
          :disabled="isDisabled"
          :required="true"
        ></select-user>
        <select-org
          title="测试部门"
          :deptId.sync="formData.departmentId"
          :deptName.sync="formData.departmentName"
          :disabled="isDisabled"
          :required="true"
        ></select-org>

        <!--明细表-->
        <detail-table
          :tableColumn="tableColumn.reimburseAttachementList"
          :formDetail.sync="detailTable.reimburseAttachementList"
          tableName="申请报销子表附件表"
          ref="detailForm0"
          :tableType="type"
          :required="true"
          :readonly="isDisabled ? 'readonly' : ''"
        ></detail-table>
        <detail-table
          :tableColumn="tableColumn.reimburseDetailList"
          :formDetail.sync="detailTable.reimburseDetailList"
          tableName="申请报销子表"
          ref="detailForm0"
          :tableType="type"
          :required="true"
          :readonly="isDisabled ? 'readonly' : ''"
        ></detail-table>
      </fm-form>
      <div class="form-button" v-if="type != 'view'">
        <fm-button
          round
          block
          type="primary"
          native-type="submit"
          @click="onSubmit"
          :loading="submitLoading"
          class="save-btn"
          >保存</fm-button
        >
      </div>
    </div>
  </div>
</template>
<script>
import { ENUM } from '@/store/State/stateTypes'
import {
  getCommonFormDetail,
  editCommonFormDetail,
  addCommonFormDetail,
} from './api'
import selectOrg from '@/components/select-org'
import Uploader from '@/components/upload/Uploader.vue'
import DetailTable from '@/modules/FormCenter/components/DetailTable'
import selectUser from '@/components/select-user'
import SelectPersonnel from '@/components/select-personnel'
import {
  NavBar,
  Form,
  Field,
  Calendar,
  Button,
  Stepper,
  Popup,
  Picker,
  Checkbox,
  CheckboxGroup,
  Toast,
  Cell,
  CellGroup,
  Sidebar,
  SidebarItem,
  Dialog,
} from 'fawkes-mobile-lib'
import dayjs from 'dayjs'
export default {
  name: 'index',
  components: {
    [NavBar.name]: NavBar,
    [Form.name]: Form,
    [Field.name]: Field,
    [Calendar.name]: Calendar,
    [Button.name]: Button,
    [Stepper.name]: Stepper,
    [Popup.name]: Popup,
    [Picker.name]: Picker,
    [Checkbox.name]: Checkbox,
    [CheckboxGroup.name]: CheckboxGroup,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Sidebar.name]: Sidebar,
    [SidebarItem.name]: SidebarItem,
    [Dialog.name]: Dialog,
    selectOrg,
    Uploader,
    selectUser,
    DetailTable,
    SelectPersonnel,
  },
  data() {
    return {
      submitLoading: false,
      // isDisabled: (this.$route.params.type == 'add' || this.$route.params.type == 'edit') ? false : true,
      isDisabled: false,
      showCalendar: false, //是否展示选择日期组件
      showPicker: false, //是否展示选择报销类型组件
      checkboxGroup: ['短信'],
      smsilIsCheck: true,
      emailIsCheck: true,
      formData: {
        attachment: '', //附件
        expense: ' ', //采购预算
        departmentId: '', //部门ID
        departmentName: '', //部门
        description: '', //报销描述
        financeAssignee: '', //财务审批人
        financeAssigneeFullname: '', //财务审批人
        manageAssignee: '', //经理审批人
        manageAssigneeFullname: '', //经理审批人
        manager: '', //采购负责人
        managerFullname: '', //采购负责人
        notifyMethod: '', //通知方式
        createDate: '', //采购计划日期
        name: '', //报销名称
        reimburseType: '', //差旅类型
        reimburse_attachement: [],
        reimburse_detail: [],
      },
      loading: false,
      activeKey: 0,
      fileList: [],
      tableType: 'add',
      // 明细表列对象
      tableColumn: {
        reimburseAttachementList: [
          {
            value: '',
            prop: 'test1',
            align: 'center',
            label: '开关',
            placeholder: '请输入',
            editType: 'switch',
            disabled: false,
            //预览时显示的内容 默认：关闭/开启
            switchPreviewNames: {
              0: '否',
              1: '是',
            },
          },
          {
            value: '',
            prop: 'calendarDate',
            align: 'center',
            label: '日历单选',
            placeholder: '请选择日期',
            editType: 'calendar',
            disabled: false,
            isCalendar: false,
            type: 'single', //single：单个日期 range：日期区间
          },
          {
            value_1: '',
            value_2: '',
            prop_1: 'calendarDate1',
            prop_2: 'calendarDate2',
            align: 'center',
            label: '日历区间',
            placeholder: '请选择日期',
            editType: 'calendar',
            disabled: false,
            isCalendar: false,
            type: 'range', //single：单个日期 range：日期区间
          },
          // {
          //   value_1: '',
          //   value_2: '',
          //   prop_1: 'name',
          //   prop_2: 'fullname',
          //   align: 'center',
          //   label: '选人',
          //   placeholder: '请选择人员',
          //   editType: 'selectPersonnel',
          //   disabled: false,
          //   multiple: true,
          // },
          {
            value_1: '',
            value_2: '',
            prop_1: 'deptId',
            prop_2: 'deptName',
            align: 'center',
            label: '选部门',
            placeholder: '请选择部门',
            editType: 'selectOrg',
            disabled: false,
          },
          {
            index: 0,
            value: '',
            prop: 'fileType',
            align: 'center',
            label: '文件类型',
            edit: true,
            placeholder: '请输入',
            editType: 'input',
            readonly: false,
            disabled: false,
            required: true,
          },
          {
            index: 1,
            value: '',
            prop: 'fileName',
            align: 'center',
            label: '文件名称',
            edit: true,
            placeholder: '请输入',
            editType: 'input',
            readonly: false,
            disabled: false,
            required: true,
          },
          {
            index: 2,
            value: '',
            prop: 'attachment',
            align: 'center',
            label: '附件',
            edit: true,
            placeholder: '',
            editType: 'file',
            readonly: false,
            disabled: false,
            required: false,
          },
          {
            index: 3,
            value: '',
            prop: 'description',
            align: 'center',
            label: '描述',
            edit: true,
            placeholder: '请输入',
            editType: 'textarea',
            readonly: false,
            disabled: false,
            required: true,
          },
        ],
        reimburseDetailList: [
          {
            index: 0,
            value: '',
            prop: 'reimburseType',
            align: 'center',
            label: '报销类型',
            edit: true,
            placeholder: '请选择',
            editType: 'select',
            dictCode: 'reimburse_type',
            readonly: false,
            disabled: false,
            required: false,
          },
          {
            index: 1,
            value: '',
            prop: 'name',
            align: 'center',
            label: '报销名称',
            edit: true,
            placeholder: '请输入',
            editType: 'input',
            readonly: false,
            disabled: false,
            required: true,
          },
          {
            index: 2,
            value: '',
            prop: 'reimburseFee',
            align: 'center',
            label: '报销费用',
            edit: true,
            placeholder: '请输入',
            editType: 'number',
            readonly: false,
            disabled: false,
            required: true,
          },
          {
            index: 3,
            value: '',
            prop: 'reimburseDate',
            align: 'center',
            label: '报销日期',
            edit: true,
            placeholder: '请选择',
            editType: 'datePicker',
            readonly: false,
            disabled: false,
            required: true,
            format: 'YYYY-MM-DD HH:mm:ss',
          },
          {
            index: 4,
            value: '',
            prop: 'description',
            align: 'center',
            label: '报销描述',
            edit: true,
            placeholder: '请输入',
            editType: 'textarea',
            readonly: false,
            disabled: false,
            required: true,
          },
        ],
      },
      // 明细表对象
      detailTable: {
        reimburseAttachementList: [],
        reimburseDetailList: [],
      },
      // 明细表实体名数组
      detailEntityNameList: ['reimburseAttachementList', 'reimburseDetailList'],
      //selectPersonnel组件测试
      name1: '',
      fullname1: '',
      name2: '',
      fullname2: '',
    }
  },
  watch: {
    name1() {
      console.log(this.name1)
      console.log(this.fullname1)
    },
    name2() {
      console.log(this.name2)
      console.log(this.fullname2)
    },
  },
  computed: {
    id() {
      return this.$router.currentRoute.params.id
    },
    type() {
      return this.$router.currentRoute.params.type
    },
    // 主表分类字典 //选择器字段
    reimburseType() {
      return this.$store.state[ENUM][this.toLine('reimburse_type')] || []
    },
    lang() {
      if (this.$storage.get('i18nLocale') == 'zh') {
        return 'zh-CN'
      } else {
        return 'en'
      }
    },
  },
  mounted() {
    this.tableType = this.type
    if (this.type != 'add') {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
      })
      this.getFromDetail()
    }
    if (this.type == 'view') {
      this.isDisabled = true
    }
    if (this.type == 'add') {
      this.loading = true
      this.checkbox('短信')
    }
    this.formData.createDate = this.$dayjs().format('YYYY-MM-DD')
  },
  methods: {
    // 限制步进器最多只能三位小数
    stepperChange(val) {
      // 当有值或为数字时判断
      if (val === '' || val == null || isNaN(val)) {
        return false
      }
      let reg = /^\d+\.?\d{0,3}$/
      let newVal = null
      if (!reg.test(val)) {
        Toast('限制正数或3位小数')
        val = val.toString()
        newVal =
          val.indexOf('.') > -1 ? val.slice(0, val.indexOf('.') + 4) : val
        setTimeout(() => {
          this.$set(this.formData, 'expense', newVal)
        }, 500)
      }
    },
    getFromDetail() {
      getCommonFormDetail({
        id: this.id,
        entityName: 'Reimbursement',
        detailEntityNameList: ['ReimburseDetail', 'ReimburseAttachement'],
      })
        .then((res) => {
          let data = res.data.entityObject
          data.createDate =
            data.createDate == null ? null : data.createDate.split(' ')[0]
          this.formData = data
          this.formData.reimburseType = data.type
          // 判断邮箱短信的选中状态
          if (data.notifyMethod != null) {
            this.checkboxGroup = data.notifyMethod.split(',')
          }
          this.detailTable.reimburseAttachementList =
            res.data.detailParamList[1].detailEntityArray
          this.detailTable.reimburseDetailList =
            res.data.detailParamList[0].detailEntityArray
        })
        .finally(() => {
          Toast.clear()
          this.loading = true
        })
    },
    onSubmit() {
      // console.log('this.detailTable', this.detailTable)
      // console.log('this.tableColumn', this.tableColumn)
      if (!this.formData.managerFullname) {
        return Toast('请选择采购负责人')
      }
      if (!this.formData.financeAssigneeFullname) {
        return Toast('请选择财务审批人')
      }
      if (!this.formData.manageAssigneeFullname) {
        return Toast('请选择经理审批人')
      }
      if (!this.formData.departmentName) {
        return Toast('请选择测试部门')
      }
      if (this.detailTable.reimburseAttachementList.length == 0) {
        return Toast('申请报销子表附件表不能为空')
      }
      if (this.detailTable.reimburseDetailList.length == 0) {
        return Toast('申请报销子表不能为空')
      }
      this.submitLoading = true
      // 如果有上传文件，则合并文件filetoken为groupToken
      if (this.fileList.length > 0) {
        // 屏蔽watch监听附件值变更重新获取文件
        this.$refs.attachment.needToGetFile = false
        this.$refs.attachment.setG9s()
      } else {
        this.formData.attachment = ''
      }
      let temp = JSON.parse(JSON.stringify(this.formData))
      temp.createDate = this.$dayjs(temp.createDate).format(
        'YYYY-MM-DD HH:mm:ss'
      )
      temp.type = temp.reimburseType
      let data = {
        entityName: 'Reimbursement',
        entityObject: Object.assign({}, temp),
        detailParamList: [
          {
            detailEntityArray: this.detailTable.reimburseAttachementList,
            detailEntityName: 'reimburseAttachement',
          },
          {
            detailEntityArray: this.detailTable.reimburseDetailList,
            detailEntityName: 'reimburseDetail',
          },
        ],
      }
      if (this.type == 'add') {
        addCommonFormDetail(data).then((res) => {
          if (res.status) {
            Toast('保存成功')
            setTimeout(() => {
              this.$router.go(-1)
            }, 1000)
          } else {
            Toast(res.message)
          }
        })
      } else {
        editCommonFormDetail(data).then((res) => {
          if (res.status) {
            Toast('编辑成功')
            setTimeout(() => {
              this.$router.go(-1)
            }, 1000)
          } else {
            Toast(res.message)
          }
        })
      }
    },
    // 确认选择日期组件
    onCalendarConfirm(date) {
      this.formData.createDate = this.$dayjs(date).format('YYYY-MM-DD')
      this.showCalendar = false
    },
    // 确认选择差旅类型组件
    onReimburseTypeConfirm(value) {
      this.formData.reimburseType = value.code
      this.showPicker = false
    },
    checkbox(value) {
      this.formData.notifyMethod = value.toString()
    },
    // 驼峰转换下划线
    toLine(name) {
      return name.replace(/([A-Z])/g, '_$1').toLowerCase()
    },
    fileChange(item) {
      this.fileList = item.fileList
    },
  },
}
</script>

<style scoped lang="less">
* {
  box-sizing: border-box;
}
.main-container {
  height: 100%;
  background: #fff;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.main,
.cus-form {
  overflow: auto;
  flex: 1;
}

.with-button,
.cus-form {
  height: calc(100% - 122px - env(safe-area-inset-bottom));
  height: calc(100% - 122px - constant(safe-area-inset-bottom));
}

.without-button {
  height: calc(100% - 92px);
  .cus-form {
    height: 100%;
  }
}

/deep/.fm-field--disabled .fm-field__label {
  color: #000;
}
/deep/ .fm-sidebar-item {
  padding: 24px 24px;
}
/deep/ .fm-sidebar-item__text {
  width: 200px;
}
/deep/ .fm-cell-group__title {
  color: #000;
}

.field-attachment {
  flex-direction: column;
  /deep/ .fm-field__control--right {
    justify-content: flex-start;
  }
}

.form-button {
  display: flex;
  padding: 18px 30px;
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(0 + env(safe-area-inset-bottom));
  bottom: calc(0 + constant(safe-area-inset-bottom));
  height: 122px;

  .save-btn {
    z-index: -1;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

/deep/.fm-button--primary {
  background-color: #4545d1;
  border: 0.02667rem solid #4545d1;
}

.textarea-type /deep/ .fm-field__value {
  border: 1px solid #bbbbbb;
  opacity: 0.5;
}
.textarea-type /deep/ .fm-field--min-height .fm-field__control {
  padding-left: 20px;
  padding-top: 20px;
}
.textarea-type /deep/ .fm-field__word-limit {
  margin-right: 20px;
  margin-bottom: 12px;
}
</style>
